package com.jdew.thkj.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.JDLeiMuAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.JDListBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.WrapContentGridLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/8.
 */

public class JDPartActivity extends BaseActivity {
    @Bind(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.price)
    RadioButton price;
    @Bind(R.id.main_tab)
    RadioGroup main_tab;
    @Bind(R.id.yj)
    RadioButton yj;
    @Bind(R.id.down)
    TextView down;
    @Bind(R.id.newst)
    RadioButton newst;
    @Bind(R.id.hot)
    RadioButton hot;
    @Bind(R.id.search)
    TextView search;
    @Bind(R.id.iv_1)
    ImageView iv1;
    @Bind(R.id.iv_2)
    ImageView iv2;
    @Bind(R.id.iv_3)
    ImageView iv3;
    @Bind(R.id.iv_4)
    ImageView iv4;
    @Bind(R.id.iv_5)
    ImageView iv5;
    @Bind(R.id.iv_6)
    ImageView iv6;
    @Bind(R.id.iv_7)
    ImageView iv7;
    @Bind(R.id.iv_8)
    ImageView iv8;
    @Bind(R.id.iv_9)
    ImageView iv9;
    @Bind(R.id.iv_10)
    ImageView iv10;
    private JDLeiMuAdapter adapter;
    private List<JDListBean.DataBean> list = new ArrayList<>();
    private int page = 1;
    private String itemId;
    private Dialog mWeiboDialog;
    private Boolean paixun = false;
    private Boolean pricepaixun = false;
    private String sort = "0";
    private String sortby = "desc";

    @Override
    public int bindLayout() {
        return R.layout.activity_jd_part;
    }

    @Override
    public void initView(View view) {
        title.setText("京东");
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        down.setVisibility(View.GONE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        RadioButton rb = (RadioButton) main_tab.getChildAt(0);
        rb.setChecked(true);
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        adapter = new JDLeiMuAdapter(this, list);
        recycleView.setLayoutManager(new WrapContentGridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        recycleView.setAdapter(adapter);
        RequestData();
        yj.setCompoundDrawables(null, null, drawable, null);
        newst.setOnClickListener(this);
        yj.setOnClickListener(this);
        hot.setOnClickListener(this);
        price.setOnClickListener(this);
        search.setOnClickListener(this);
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        iv4.setOnClickListener(this);
        iv5.setOnClickListener(this);
        iv6.setOnClickListener(this);
        iv7.setOnClickListener(this);
        iv8.setOnClickListener(this);
        iv9.setOnClickListener(this);
        iv10.setOnClickListener(this);
        price.setCompoundDrawables(null, null, drawable, null);
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(JDPartActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemId = list.get(position).getSkuId();
                    toDetail();
                }
            }
        });
        RequestData();
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(this));
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(this));
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                RequestData();
                smartRefreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                RequestData();
                smartRefreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.search: {
                Bundle b = new Bundle();
                b.putSerializable("source", "jd");
                startActivity(MainSearchActivity.class, b);
            }
            break;
            case R.id.newst: {
                Drawable drawable1 = getResources().getDrawable(R.mipmap.price_normal);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                sort = "0";
                price.setCompoundDrawables(null, null, drawable1, null);
                yj.setCompoundDrawables(null, null, drawable1, null);
                page = 1;
                RequestData();
            }
            break;
            case R.id.yj: {
                price.setCompoundDrawables(null, null, drawable, null);
                sort = "4";
                if (!paixun) {
                    Drawable drawable2 = getResources().getDrawable(R.mipmap.price_down);
                    drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
                    yj.setCompoundDrawables(null, null, drawable2, null);
                    sortby = "desc";
                    paixun = true;
                } else {
                    Drawable drawable3 = getResources().getDrawable(R.mipmap.price_up);
                    drawable3.setBounds(0, 0, drawable3.getMinimumWidth(), drawable3.getMinimumHeight());
                    yj.setCompoundDrawables(null, null, drawable3, null);
                    paixun = false;
                    sortby = "asc";
                }
                page = 1;
                RequestData();
            }
            break;
            case R.id.hot: {
                Drawable drawable4 = getResources().getDrawable(R.mipmap.price_normal);
                drawable4.setBounds(0, 0, drawable4.getMinimumWidth(), drawable4.getMinimumHeight());
                sortby = "desc";
                sort = "2";
                price.setCompoundDrawables(null, null, drawable4, null);
                yj.setCompoundDrawables(null, null, drawable4, null);
                page = 1;
                RequestData();
            }
            break;
            case R.id.price: {
                yj.setCompoundDrawables(null, null, drawable, null);
                sort = "1";
                if (!pricepaixun) {
                    Drawable drawable5 = getResources().getDrawable(R.mipmap.price_down);
                    drawable5.setBounds(0, 0, drawable5.getMinimumWidth(), drawable5.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable5, null);
                    sortby = "desc";
                    pricepaixun = true;
                } else {
                    Drawable drawable6 = getResources().getDrawable(R.mipmap.price_up);
                    drawable6.setBounds(0, 0, drawable6.getMinimumWidth(), drawable6.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable6, null);
                    pricepaixun = false;
                    sortby = "asc";
                }
                page = 1;
                RequestData();
            }
            break;
            case R.id.iv_1:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "1620");
                startActivity(intent);
            }
            break;
            case R.id.iv_2:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "1320");
                startActivity(intent);
            }
            break;
            case R.id.iv_3:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "1319");
                startActivity(intent);
            }
            break;
            case R.id.iv_4:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "737");
                startActivity(intent);
            }
            break;
            case R.id.iv_5:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "9987");
                startActivity(intent);
            }
            break;
            case R.id.iv_6:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "652");
                startActivity(intent);
            }
            break;
            case R.id.iv_7:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "670");
                startActivity(intent);
            }
            break;
            case R.id.iv_8:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "1315");
                startActivity(intent);
            }
            break;
            case R.id.iv_9:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "1316");
                startActivity(intent);
            }
            break;
            case R.id.iv_10:{
                Intent  intent = new Intent(this, JDSearchActivity.class);
                intent.putExtra("cid", "11729");
                startActivity(intent);
            }
            break;
            default:
                break;
        }
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            }
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("pageIndex", page);
        map.put("sortby", sortby);
        map.put("sort", sort);
        if (null == mWeiboDialog || !mWeiboDialog.isShowing()) {
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Displaylist(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "")  + "pageIndex" + page + "sortby" + sortby + "sort" + sort)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JDListBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JDListBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null == bean.getData() && list.size() == 0) {
                        list.clear();
                        adapter.setDataList(list);
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                        adapter.setDataList(list);
                    }
                    list.addAll(bean.getData());
                    if (bean.getData().size() < 20 && bean.getData().size() >= 0) {
                        smartRefreshLayout.setEnableLoadMore(false);
                    }
                    adapter.setDataList(list);
                }
            }
        });
    }

//    public void setRecycleView() {
//        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//                LinearLayoutManager linearManager = null;
//                if (layoutManager instanceof LinearLayoutManager) {
//                    linearManager = (LinearLayoutManager) layoutManager;
//                }
//                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
//                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
//                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
//                    if (isRefreshing) {
//                        adapter.notifyItemRemoved(adapter.getItemCount());
//                        return;
//                    }
//                    if (!isLoading) {
//                        isLoading = true;
//                        page++;
//                        RequestData();
//                    }
//                }
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//            }
//        });
//    }

    public void toDetail() {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemId);
        startActivity(JDProductDetailActivity.class, b);
    }
}
